import { CheckOutlined, CloseOutlined } from "@ant-design/icons";
import { Input, Select, Button, Drawer, Switch } from "antd";
import { findIndex } from "lodash";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";

import { ChartItem, ChartType } from "../../modules/workspace/models";
import ColorPicker from "../ColorPicker";

import { useWorkSpace } from "~/modules/workspace/store/use-workspace";
import "./index.scss";
import { axisData } from "~/modules/worker/schedule";

import { getStateParamsOPtions, getParamsOptions } from "./utils";

const chartTypeOptions: { label: string; value: string }[] = [
  { label: "区域图", value: "lineArea" },
  { label: "折线图", value: "line" },
  { label: "散点图", value: "scatter" },
];
interface Props {
  name: string;
  chartNum: number;
  isMerge: boolean;
  chartChange: Function;
}
const ChartPropertySettings = (props: Props, ref: any) => {
  // 弹出层 显示隐藏
  const [isOpen, setIsOpen] = useState<boolean>(false);
  //获取工作区图表配置
  const { workSpace, update } = useWorkSpace();

  // 图表高度
  const [chartHight, setChartHight] = useState<string>("");
  //抛面图参数
  const [paramsOptions, setParamsOptions] = useState<
    { label: string; value: string }[]
  >([]);
  // 状态量参数
  const [stateQuantityParameter, setStateQuantityParameter] = useState<
    { label: string; value: string }[]
  >([]);
  // 滑动条参数
  const [params, setParams] = useState<string>("");
  // 状态量参数
  const [stateParams, setStateParams] = useState("");
  // 是否根据状态量设置背景
  const [isBgColor, setIsBgColor] = useState<boolean>(true);
  // 背景色1
  const [color1, setColor1] = useState<string>("#F6464A");
  const [color2, setColor2] = useState<string>("#1F7EAD");
  const [chartItem, setChartItem] = useState<ChartItem>({
    name: "",
    chartType: ChartType.LINE,
    upperLimit: "",
    lowerLimit: "",
    XOffset: "",
    YOffset: "",
    IsTop: false,
    data: [],
  });
  useEffect(() => {
    if (props.name !== "数据表") {
      const chart = workSpace.splitCharts[props.chartNum];
      if (chart) setChartItem(chart);
      setParamsOptions(getParamsOptions(workSpace.splitCharts));
      setStateQuantityParameter(getStateParamsOPtions(workSpace.splitCharts));
      const name = workSpace.splitCharts[0]
        ? workSpace.splitCharts[0].data[0]?.title
        : "";
      setParams(name);
      setStateParams(workSpace.setting.stateQuantityParams);
      setColor1(workSpace.setting.backgroundColors[0] ?? "");
      setColor2(workSpace.setting.backgroundColors[1] ?? "");
      setChartHight(workSpace.setting.chartsHeight);
      setIsBgColor(workSpace.setting.setBgByStateQuantity);
    }
  }, [isOpen]);

  // 选择抛面图参数
  const onChangePlanedParams = (label: string, value: any) => {
    setParams(value.label);
    let charts: any[] = [];
    charts = workSpace.splitCharts;

    for (let i = 0; i < charts.length; i++) {
      for (let k = 0; k < charts[i].data.length; k++) {
        if (charts[i].data[k].title === value.label) {
          const chart = charts[i];
          const param = charts[i].data[k];
          workSpace.splitCharts[i].data.splice(k, 1);
          workSpace.splitCharts[i].data.unshift(param);
          workSpace.splitCharts.splice(i, 1);
          workSpace.splitCharts.unshift(chart);
          return;
        }
      }
    }
  };

  // 更新/保存
  const onUpdate = () => {
    axisData.offsetAxisData = [];
    workSpace.setting.chartsHeight = chartHight;
    workSpace.setting.profileChartParmas = params;
    workSpace.setting.setBgByStateQuantity = isBgColor;
    workSpace.setting.stateQuantityParams = stateParams;
    workSpace.setting.backgroundColors = [color1, color2];
    const n = findIndex(workSpace.splitCharts, (item) => {
      return item.name === props.name;
    });
    workSpace.splitCharts[n] = chartItem;
    update(workSpace);
    props.chartChange();
    setIsOpen(false);
  };
  // 打开抽屉
  const onOpen = () => {
    setIsOpen(true);
  };
  // 向父组件暴露关闭抽屉方法
  useImperativeHandle(ref, () => ({
    onOpen,
  }));
  return (
    <>
      <Drawer
        placement="right"
        width="20%"
        bodyStyle={{ padding: "16px 16px 0" }}
        closable={false}
        open={isOpen}
      >
        <div className="pb-64px" style={{ position: "relative" }}>
          <p
            className="text-16px font-700 color-#363F4D m-0"
            style={{ lineHeight: "38px" }}
          >
            属性配置
          </p>
          <p
            className="text-14px font-700 color-#363F4D m-0"
            style={{ lineHeight: "32px" }}
          >
            图表属性
          </p>
          <p
            className="text-12px color-#9B9FA6 mt-10px mb-10px"
            style={{ lineHeight: "12px" }}
          >
            图表类型：
          </p>
          <Select
            value={chartItem.chartType}
            placeholder="请选择"
            style={{ width: "100%" }}
            options={chartTypeOptions}
            onChange={(e) => {
              setChartItem({ ...chartItem, chartType: e });
            }}
          />

          <div className="flex">
            <div className="w-49% mr-5px">
              <p
                className="text-12px color-#9B9FA6 mt-10px mb-10px"
                style={{ lineHeight: "12px" }}
              >
                数据上限：
              </p>
              <Input
                value={chartItem.upperLimit}
                placeholder="数据上限"
                onChange={(e) =>
                  setChartItem({ ...chartItem, upperLimit: e.target.value })
                }
              />
            </div>
            <div style={{ marginTop: "32px" }}>—</div>

            <div className="w-49% ml-5px">
              <p
                className="text-12px color-#9B9FA6 mt-10px mb-10px"
                style={{ lineHeight: "12px" }}
              >
                数据下限：
              </p>
              <Input
                value={chartItem.lowerLimit}
                status={
                  chartItem.lowerLimit !== "" &&
                  chartItem.upperLimit === chartItem.lowerLimit
                    ? "error"
                    : ""
                }
                placeholder="数据下限"
                onChange={(e) =>
                  setChartItem({ ...chartItem, lowerLimit: e.target.value })
                }
              />
            </div>
          </div>

          <div className="flex mb">
            <div className="w-49% mr-5px">
              <p
                className="text-12px color-#9B9FA6 mt-10px mb-10px"
                style={{ lineHeight: "12px" }}
              >
                X轴偏移量(秒)：
              </p>
              <Input
                value={chartItem.XOffset}
                placeholder="X轴偏移量(秒)"
                onChange={(e) =>
                  setChartItem({ ...chartItem, XOffset: e.target.value })
                }
              />
            </div>
            <div style={{ marginTop: "32px" }}>—</div>
            <div className="w-49% ml-5px">
              <p
                className="text-12px color-#9B9FA6 mt-10px mb-10px"
                style={{ lineHeight: "12px" }}
              >
                Y轴偏移量：
              </p>
              <Input
                value={chartItem.YOffset}
                placeholder="Y轴偏移量"
                onChange={(e) =>
                  setChartItem({ ...chartItem, YOffset: e.target.value })
                }
              />
            </div>
          </div>
          <p
            className="text-14px font-700 color-#363F4D m-0"
            style={{ lineHeight: "32px" }}
          >
            工作区属性
          </p>
          <p
            className="text-12px color-#9B9FA6 mt-10px mb-10px"
            style={{ lineHeight: "12px" }}
          >
            刨面图参数：
          </p>
          <Select
            value={params}
            showSearch
            placeholder="请选择"
            optionFilterProp="label"
            style={{ width: "100%" }}
            options={paramsOptions}
            onChange={(val, label) => onChangePlanedParams(val, label)}
          />
          <p
            className="text-12px color-#9B9FA6 mt-10px mb-10px"
            style={{ lineHeight: "12px" }}
          >
            图表高度：
          </p>
          <Input
            value={chartHight}
            placeholder="请输入"
            onChange={(e) => setChartHight(e.target.value)}
          />
          <p
            className="text-12px color-#9B9FA6 mt-10px mb-10px"
            style={{ lineHeight: "12px" }}
          >
            根据状态量参数设置背景：
          </p>
          <Switch
            checked={isBgColor}
            size="small"
            defaultChecked
            onChange={(e) => setIsBgColor(e)}
          />
          <p
            className="text-12px color-#9B9FA6 mt-10px mb-10px"
            style={{ lineHeight: "12px" }}
          >
            选择状态量参数：
          </p>
          <Select
            className="w-100%!"
            value={stateParams ? stateParams : null}
            showSearch
            placeholder="选择状态量参数"
            optionFilterProp="label"
            filterOption={(input, option) =>
              (option?.label ?? "").toLowerCase().includes(input.toLowerCase())
            }
            options={stateQuantityParameter}
            onChange={(val) => setStateParams(val)}
          />
          <p
            className="text-12px color-#9B9FA6 mt-10px mb-10px"
            style={{ lineHeight: "12px" }}
          >
            背景色：
          </p>
          <div className="flex">
            <div className="w-49% mr-5px">
              <ColorPicker
                color={color1}
                change={(color: string) => setColor1(color)}
              />
            </div>
            —
            <div className="w-49% ml-5px">
              <ColorPicker
                color={color2}
                change={(color: string) => {
                  setColor2(color);
                }}
              />
            </div>
          </div>
        </div>

        <div
          className="h-64px bottom-0 bg-#FFF pt-16px"
          style={{ width: "calc(100% - 32px)", position: "absolute" }}
        >
          <div className="flex justify-between">
            <Button icon={<CloseOutlined />} onClick={() => setIsOpen(false)}>
              取消
            </Button>
            <Button
              type="primary"
              icon={<CheckOutlined />}
              onClick={() => onUpdate()}
            >
              更新
            </Button>
          </div>
        </div>
      </Drawer>
    </>
  );
};

export default forwardRef(ChartPropertySettings);
